package v1;

import org.bson.Document;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * @Author: jiarupc
 * @Date: 2020/12/13
 * @Description:
 */
public class Order {
    private Long id;
    private Long userId;
    private String orderNo;
    private BigDecimal amount;
    private String createTime;
    private String updateTime;
    // 省略无数字段

    public static Document order2Doc(Order order) throws Exception {
        Document doc = new Document();

        // 获取所有字段：通过 getClass() 方法获取 Class 对象，然后获取这个类所有字段
        Field[] fields = order.getClass().getDeclaredFields();
        for (Field field : fields) {
            // 开放字段操作权限
            field.setAccessible(true);
            // 设置值
            doc.put(field.getName(), field.get(order));
        }

        return doc;
    }

    public static Order doc2Order(Document doc) throws Exception {
        Order order = new Order();

        for (String key : doc.keySet()) {
            // 获取字段
            Field field = order.getClass().getDeclaredField(key);
            // 开放字段操作权限
            field.setAccessible(true);
            // 设置值
            field.set(order, doc.get(key));
        }

        return order;
    }

    public static void main(String[] args) throws Exception {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(0L);
        order.setOrderNo("1");
        order.setAmount(new BigDecimal("0"));
        order.setCreateTime("2");
        order.setUpdateTime("3");
        System.out.println(order);

        Document document = order2Doc(order);
        System.out.println(document);

        Order order1 = doc2Order(document);
        System.out.println(order1);
    }










        // getter/setter
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }


}
